import Vue from 'vue';
import Vuex from 'vuex';
import Web3 from 'web3';

//模块化store
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    account: '',
    net: 0,
  },
  mutations: {

    SETACCOUNTS: (state, account) => {
      state.account = account;
    },
    SETNET: (state, net) => {
      state.net = net;
    },
  },
  actions: {
    async setWallet({ commit }) {
      if (typeof window.ethereum === "undefined") {
        //没安装MetaMask钱包进行弹框提示
        alert("请安装MetaMask");
      }
      var web3Provider;
      if (window.ethereum) {
        web3Provider = window.ethereum;
        try {
          await web3Provider.enable();
          const web3js = new Web3(web3Provider);
          web3js.eth.getAccounts(function (error, result) {
            if (!error) {
              commit('SETACCOUNTS', result[0]);
              localStorage.setItem('loginStatus', false);
            }
          });
        } catch (error) {
          console.error('User denied account access');
        }
      }
    },
    async setWebProvider({ commit }) {
      if (typeof window.ethereum === "undefined") {
        //没安装MetaMask钱包进行弹框提示
        alert("请安装MetaMask");
      }
      const loginStatus = sessionStorage.getItem('loginStatus')
      if (loginStatus == "true") {
        return
      }
      var web3Provider;
      if (window.ethereum) {
        web3Provider = window.ethereum;
        const web3js = new Web3(web3Provider);

        try {
          const net = await web3js.eth.net.getId()
          if (net != 1) {
            await web3Provider.request({
              method: 'wallet_switchEthereumChain',
              params: [{ chainId: '0x1' }],
            });
          }

          await web3Provider.enable();
        } catch (error) {
          console.log(error);
          console.error('User denied account access');
        }


        web3js.eth.getAccounts(function (error, result) {
          if (!error) {
            commit('SETACCOUNTS', result[0]);
          }
        });
        web3Provider.on('networkChanged', function (networkIDstring) {
          commit('SETNET', networkIDstring);
        });
        web3Provider.on('accountsChanged', function (accounts) {
          commit('SETACCOUNTS', accounts[0]);
        });
      }
    },
  },
});
